package com.ws.function.javascript.base;

import java.io.FileReader;
import java.io.IOException;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.ws.base.common.util.WSUtil;

public final class JavascriptSupport {
    private String filepath;

    private JavascriptSupport() {
    }

    private static class SingletonHolder {
        private final static JavascriptSupport INSTANCE = new JavascriptSupport();
    }

    public static JavascriptSupport getInstance(String filepath) {
        JavascriptSupport javascriptSupport = SingletonHolder.INSTANCE;
        javascriptSupport.filepath = filepath;
        return javascriptSupport;
    }

    public Object execute(String functionName, Object... args)
            throws ScriptException, NoSuchMethodException, IOException {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByExtension("js");
        FileReader fileReader = new FileReader(filepath);
        engine.eval(fileReader);
        Invocable inv = (Invocable) engine;
        Object callback = inv.invokeFunction(functionName, args);
        WSUtil.close(fileReader);
        return callback;
    }

}
